from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from apps.models import SysDict, SysDictDetail
from apps.system import schemas
from core.crud import DalBase


class DictDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(DictDal, self).__init__()
        self.db = db
        self.model = SysDict
        self.schema = schemas.DictSimpleOut

    async def get_dicts_details_options(self) -> dict:
        """
        获取多个字典类型下的字典元素列表
        """
        data = {}
        options = [joinedload(self.model.details)]
        objs = await DictDal(self.db).get_datas(
            limit=0,
            v_return_objs=True,
            v_options=options
        )
        for obj in objs:
            if not obj:
                data[obj.code] = []
                continue
            else:
                data[obj.code] = [schemas.DictDetailSimpleOut.model_validate(i).model_dump() for i in obj.details]
        return data


class DictDetailDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(DictDetailDal, self).__init__()
        self.db = db
        self.model = SysDictDetail
        self.schema = schemas.DictDetailSimpleOut
